package com.example.im.ui.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.R
import com.example.im.bean.UserRoom
import com.example.im.callback.OnClickRoomListener
import com.example.im.common.Constants
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.ui.adapter.RoomOwnerAdapter
import com.example.im.db.DatabaseStorage
import kotlinx.android.synthetic.main.fragment_room_owner.*

class RoomOwnerFragment : AbstractBaseFragment<BasePresenter<*>>() {


    private var adapter: RoomOwnerAdapter? = null

    private var mOnClickRoomListener: OnClickRoomListener? = null

    companion object {
        fun newInstance(owners: ArrayList<UserRoom>): RoomOwnerFragment {
            val bundle = Bundle()
            bundle.putSerializable(Constants.BUNDLE_T0_USER_ROOM_DATA, owners)
            val fragment = RoomOwnerFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mOnClickRoomListener = context as OnClickRoomListener
    }

    override val layoutId: Int
        get() = R.layout.fragment_room_owner

    override fun initView() {

        val arrayList = arguments!!.getSerializable(Constants.BUNDLE_T0_USER_ROOM_DATA)
                as ArrayList<*>

        val owners = mutableListOf<UserRoom>()
        arrayList.forEach { owners.add(it as UserRoom) }

        val account = DatabaseStorage.getAccountInfoStorage()

        val isOwner = owners[0].account == account.username

        tv_room_delete_owner.visibility =
            if (isOwner) View.VISIBLE else View.GONE

        if (owners.isNotEmpty()) {
            tv_name.text = owners[0].nickname
            owners.removeAt(0)
        }
        if (owners.isEmpty()) {
            tv_room_delete_owner.visibility = View.GONE
        }

        adapter = RoomOwnerAdapter(activity!!, owners, isOwner)
        recycler_view.layoutManager = LinearLayoutManager(activity!!)
        recycler_view.adapter = adapter

        tv_room_delete_owner.setOnClickListener {
            mOnClickRoomListener!!.onClickUserKick(it, adapter!!.getSelectedItem())
        }
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }
}